<?php

namespace App\Http\Controllers\home;

use App\Http\Models\Course;
use App\Http\Models\Order;
use App\Http\Models\OrderCourse;
use App\Tools\Cart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//文件头use一下
use EchoBool\AlipayLaravel\Facades\Alipay;

class ShopController extends Controller
{
    //购物车
    public function cart_account(){
        //已在中间件中判断用户是否登录  这里重复了
//        if(!(\Auth::guard('front')->check())){
//            return redirect()->guest('home/login/index');
//        }
        $cart = new Cart();
        //获取购物车中的课程信息
        $courseinfo = $cart->getCartInfo();
        $course=[];
        $number_price=[];
        //当购物车里面有商品时执行
        if($courseinfo){
            //获取购物车中商品的数量和总价格
            $number_price = $cart->getNumberPrice();
            //遍历数组取出课程ID 用于查询课程详细信息`
//        foreach($courseinfo as $course){
//            $course_ids[]=$course['course_id'];
//        }
            $course_ids = array_keys($courseinfo);
            //根据取出的课程ID查询课程信息
            $course = Course::whereIn('course_id',$course_ids)->get()->toArray();
            //当购物车里没数据时
        }




        return view('home.shop.cart_account',compact('course','number_price'));
    }

    //删除购物车里的商品
    public function del($course){
        $cart = new Cart();
        $cart->del($course);
        //获取购物车中商品的数量和总价格
        $number_price = $cart->getNumberPrice();
        return ['success'=>true,'index'=>$course,'info'=>$number_price];
    }

    //购物车结算
    public function cart_pay(){
        $cart = new Cart();
        //获取购物车信息
        $cart_info = $cart->getCartInfo();
        //获取商品的总数和总价格
        $price_number = $cart->getNumberPrice();
        $order_info = [
            'order_sn'    =>  uniqid('xue_'),
            'std_id'      =>  \Auth::guard('front')->user()->std_id,
            'total_price' =>   $price_number['price']
            ];
        $order = Order::create($order_info);

        foreach($cart_info as $key => $val){
            OrderCourse::create([
                'order_id'    => $order->order_id,
                'course_id'   => $key,
                'course_price'=> $val['course_price']
            ]);
        }



        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $order_info['order_sn'];
        //订单名称，必填
        $subject = '购买课程'.time();
        //付款金额，必填
        $total_amount = $price_number['price'];
        //商品描述，可空
        $body = '';

        $customData = json_encode(['model_name' => 'ewrwe', 'id' => 121]);//自定义参数
        $response = Alipay::tradePagePay($subject, $body, $out_trade_no, $total_amount, $customData);
        //输出表单
        return $response['redirect_url'];
    }

    //支付完成 回传get请求
    public function return_url(Request $request){
//        echo '<pre>';
//        print_r($_GET);
//        echo '</pre>';
//        exit();
        //验证回传的GET请求
        $result = Alipay::notify($_GET);

        //判断验证是否成功
        if($result){
            //商品订单号
            $out_trade_no = htmlspecialchars($_GET['out_trade_no']);
            //支付宝交易号
            $trade_no = htmlspecialchars($_GET['trade_no']);
            //实现订单有未付款 变为 已付款
            $res = Order::where('order_sn',$out_trade_no)
                ->update([
                    'trade_sn'  => $trade_no,
                    'pay_money' => $_GET['total_amount'],
                    'pay_time'  => strtotime($_GET['timestamp']),
                    'pay_status'=> '是',
                ]);
            if($res){
                //清空购物车
                (new Cart())->delall();
                //展示付款成功页面
                return view('home.shop.return_url');
            }else{
                echo '付款成功,数据库更新失败';
            }
        }else{
            //验证失败
            echo '验证失败';
        }
    }
}
